package by.alex.dzeshko.facebooksuperclient;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import by.alex.dzeshko.facebooksuperclient.adapter.FeedCursorAdapter;
import by.alex.dzeshko.facebooksuperclient.api.ApiRequest;
import by.alex.dzeshko.facebooksuperclient.constants.FbConstants;
import by.alex.dzeshko.facebooksuperclient.database.DbNewsfeedHelper;
import by.alex.dzeshko.facebooksuperclient.database.DbUsersHelper;
import by.alex.dzeshko.facebooksuperclient.http.RequestBuilder;
import by.alex.dzeshko.facebooksuperclient.image.ImageLoader;
import by.alex.dzeshko.facebooksuperclient.providers.contract.FbContract;
import by.alex.dzeshko.facebooksuperclient.service.FeedService;
import by.alex.dzeshko.facebooksuperclient.service.ProfileService;
import by.alex.dzeshko.facebooksuperclient.utils.InetChecker;
import by.alex.dzeshko.facebooksuperclient.utils.ViewHider;

public class UserProfileActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {
	
	private static final String P = "P";

	private static final String TAG = "tag";

	protected static final String LOG_TAG = "UserProfileActivity";

	private TextView mTextViewName, mTextViewBirthDay, mTextViewLocation;
	
	private ImageView mImageView;
	
	private ListView mListViewFeed;
	
	private Cursor mCursor;

	private DbUsersHelper mDbHelper;
		
	private String mUserId, mNextPageUrl;

	private BroadcastReceiver mHttpServiceReceiver;

	private View mViewProfileInfo, mViewLoading, mViewRefreshing;

	private FeedCursorAdapter mFeedCursorAdapter;

	private boolean mIsLoading, mScrolledDown, mViewLoadingHidden, mViewRefreshingHidden;

	private int mImageUrl;

	@Override
	protected void onCreate(Bundle bundle) {
		
		super.onCreate(bundle);
		setContentView(R.layout.activity_user_profile);
		Intent id = getIntent();
		mUserId = id.getStringExtra(FbConstants.ID);
		mScrolledDown=false;
		mListViewFeed = (ListView) findViewById(R.id.lvProfileTimeline);
		mViewProfileInfo = getLayoutInflater().inflate(R.layout.view_header_profile, null);
		mViewLoading = getLayoutInflater().inflate(R.layout.view_listitem_loading, null);
		mViewRefreshing = getLayoutInflater().inflate(R.layout.view_refreshig, null);
		mViewLoading.setTag(R.string.tag, TAG);
		mViewRefreshing.setTag(R.string.tag, TAG);
		hideViewRefreshing(true);
		hideViewLoading(true);
		mListViewFeed.addHeaderView(mViewProfileInfo);
		mListViewFeed.addHeaderView(mViewRefreshing);
		mListViewFeed.addFooterView(mViewLoading);
		mTextViewName = (TextView) mViewProfileInfo.findViewById(R.id.tvProfileName);
		mTextViewBirthDay = (TextView) mViewProfileInfo.findViewById(R.id.tvProfileAge);
		mTextViewLocation = (TextView) mViewProfileInfo.findViewById(R.id.tvProfileLocation);
		mImageView = (ImageView) mViewProfileInfo.findViewById(R.id.ivProfileImage);
	
		setProfileInfoValues();		
		
		mHttpServiceReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(ProfileService.ACTION_ON_ERROR)) {
					Toast.makeText(UserProfileActivity.this, intent.getStringExtra(ProfileService.EXTRA_KEY_MESSAGE), Toast.LENGTH_SHORT).show();
				} else if (action.equals(ProfileService.ACTION_ON_SUCCESS)) {
					setProfileInfoValues();
				} else if(action.equals(FeedService.PROFILE_FEED_ON_SUCCESS)){
					mIsLoading=false;
					if(!mViewRefreshingHidden) hideViewRefreshing(true);
					mNextPageUrl = intent.getStringExtra(FeedService.NEXT_PAGE);
					Log.d("nextProfFeed", mNextPageUrl);
					if(mNextPageUrl.equals(FeedService.NO_PAGES) || mNextPageUrl==null) hideViewLoading(true);
				} else if(action.equals(FeedService.PROFILE_FEED_ON_ERROR)){
					mIsLoading=false;
					hideViewRefreshing(true);
					hideViewLoading(true);
				}
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(ProfileService.ACTION_ON_ERROR);
		filter.addAction(ProfileService.ACTION_ON_SUCCESS);
		filter.addAction(FeedService.PROFILE_FEED_ON_SUCCESS);
		filter.addAction(FeedService.PROFILE_FEED_ON_ERROR);
		registerReceiver(mHttpServiceReceiver, filter);
		mFeedCursorAdapter = new FeedCursorAdapter(this, null);
		mListViewFeed.setAdapter(mFeedCursorAdapter);
		Bundle paramBundle = new Bundle();
		paramBundle.putString(FbConstants.USER_ID, mUserId);
		getSupportLoaderManager().initLoader(0, paramBundle, this);
		mListViewFeed.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				InetChecker.checkInetConnection(UserProfileActivity.this);
				try{
					Cursor cursor = (Cursor) parent.getItemAtPosition(position);
					Intent intent = new Intent(UserProfileActivity.this, FeedItemActivity.class);
					intent.putExtra(FbConstants.ITEM_ID, cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.ITEM_ID)));
					intent.putExtra(FbConstants.USER_ID, cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.FROM_ID)));
					intent.putExtra(FbConstants.FEED_TYPE, cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.TABLE_TYPE)));
					startActivity(intent);
				}
				catch(Exception e){
					Log.e(LOG_TAG, e.toString());
				}
			}
		});	
		
		mListViewFeed.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {	}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				if (firstVisibleItem < 2 && mScrolledDown){
					Log.d("onScroll","up scrolled");
					mScrolledDown=false;
					loadProfileImage();
				}
				if (visibleItemCount > 0 && firstVisibleItem + visibleItemCount + 2 >= totalItemCount && mNextPageUrl!=null ) {
					if(!mIsLoading && !mNextPageUrl.equals(FeedService.NO_PAGES)){
						mScrolledDown=true;
						if(mViewLoadingHidden) hideViewLoading(false);
						loadNextPage(mNextPageUrl);
						Log.d("onScroll","load "+mNextPageUrl.equals(FeedService.NO_PAGES));
					}
				}
			}
		});
	}
	
    protected void loadNextPage(String url) {
    	if(url==null){
    		mIsLoading=false;
    		return;
    	}
    	mIsLoading=true;
    	Intent intent = new Intent(this, FeedService.class);
		RequestBuilder requestBuilder = new RequestBuilder();
		requestBuilder.setType(RequestBuilder.Type.GET);
		requestBuilder.setUrl(url);
		requestBuilder.setDbMarker(FbContract.profileId(mUserId));
		intent.putExtra(FeedService.HTTP_REQUEST_BUILDER, requestBuilder);
		startService(intent);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mHttpServiceReceiver);
	}

	private void setProfileInfoValues() {
		mDbHelper = new DbUsersHelper(this, null);
		mCursor = mDbHelper.getItems();
		 if (mCursor.moveToFirst()) {		        
		        do {
		        	if(mCursor.getString(mCursor.getColumnIndex(FbContract.UserProfileColumns.ITEM_ID)).equals(mUserId)){
			    		mTextViewName.setText(mCursor.getString(mCursor.getColumnIndex(FbContract.UserProfileColumns.NAME)));
			    		mTextViewBirthDay.setText(mCursor.getString(mCursor.getColumnIndex(FbContract.UserProfileColumns.BIRTHDAY)));
			    		mTextViewLocation.setText(mCursor.getString(mCursor.getColumnIndex(FbContract.UserProfileColumns.LOCATION)));
			    		mImageUrl = mCursor.getColumnIndex(FbContract.UserProfileColumns.PICTURE_URL);
			    		loadProfileImage();
			    		mDbHelper.close();
			    		return;
		        	}
		        } while (mCursor.moveToNext());
		 }
	}

	private void loadProfileImage() {
		ImageLoader imLoader = ImageLoader.getInstance();
		imLoader.bind(mImageView, mCursor.getString(mImageUrl));
	}
	
	public void onWallPostClick(View v){
		Intent post = new Intent(this, NewPostActivity.class);
		post.putExtra(FbConstants.ID, mUserId);
		startActivity(post);
	}
		
	public void onRefreshClick(View v){
		if(!InetChecker.checkInetConnection(this)){
			return;
		}
		hideViewRefreshing(false);
		String url = ApiRequest.getProfileFeedApiUrl(mUserId);
		url = ApiRequest.addToken(url);
		DbNewsfeedHelper dbHelper = new DbNewsfeedHelper(UserProfileActivity.this, null);
		dbHelper.deleteItem(FbContract.FeedColumns.TABLE_TYPE, P+mUserId);
		loadNextPage(url+="&limit=15");
	}

	@Override
	public Loader<Cursor> onCreateLoader(int paramInt, Bundle paramBundle) {
		String where = FbContract.profileId(paramBundle.getString(FbConstants.USER_ID));
		return new CursorLoader(this, FbContract.FeedColumns.CONTENT_URI, null,
				where, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> paramLoader, Cursor paramD) {
		mFeedCursorAdapter.swapCursor(paramD);		
	}

	@Override
	public void onLoaderReset(Loader<Cursor> paramLoader) {
		mFeedCursorAdapter.swapCursor(null);		
	}

	private void hideViewRefreshing(boolean hide){
		mViewRefreshingHidden = hide;
		ViewHider.hideListItem(mViewRefreshing, hide);
	}

	private void hideViewLoading(boolean hide){
		mViewLoadingHidden = hide;
		ViewHider.hideListItem(mViewLoading, hide);
	}

}
